package com.doyens.item.controller;

import com.doyens.common.pojo.PageResult;
import com.doyens.item.pojo.Brand;
import com.doyens.item.service.BrandService;
import com.sun.org.apache.regexp.internal.RE;
import jdk.nashorn.internal.ir.BreakableNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

@RestController
@RequestMapping("/brand")
public class BrandController {

        @Autowired
        private BrandService brandService;
    /**
     *
     * @param key   查询字段
     * @param page   页码
     * @param rows   每页显示条数
     * @param sortBy  排序字段
     * @param desc  排序方式
     * @return
     */
    @GetMapping("page")
    public ResponseEntity<PageResult<Brand>> queryBrandByPage(
            @RequestParam(value = "key",required = false) String  key,
            @RequestParam(value = "page",defaultValue = "1") Integer page,
            @RequestParam(value = "rows",defaultValue = "5") Integer rows,
            @RequestParam(value = "sortBy",required = false) String sortBy,
            @RequestParam(value = "desc",required = false) Boolean desc){

            PageResult<Brand> pageResult = this.brandService.queryBrandByPage(key,page,rows,sortBy,desc);

            if (CollectionUtils.isEmpty(pageResult.getItems())){// 如果没有数据
                return ResponseEntity.notFound().build();//返回404
            }
            return ResponseEntity.ok(pageResult);

    }

    //{name:"德源", image: "", cids: "76,105", letter: "D"}
    @PostMapping
    public ResponseEntity<Void> saveBrand(Brand brand, @RequestParam("cids")List<Long> cids) {
        this.brandService.saveBrand(brand,cids);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 新增商品--分类id查询品牌列表
     *
     */
    @GetMapping("cid/{cid}")
    public ResponseEntity<List<Brand>>  queryBrandsByCid(@PathVariable("cid") Long cid){
        List<Brand>  brands =  this.brandService.queryBrandByCid(cid);
        if (CollectionUtils.isEmpty(brands)){
            return ResponseEntity.notFound().build();
        }
       return  ResponseEntity.ok(brands);
    }

    //根据品牌id查询品牌信息
    @GetMapping("/{brandId}")
    public ResponseEntity<Brand> queryById(@PathVariable("brandId") Long brandId){
        Brand brand = this.brandService.queryBrandById(brandId);
        if (StringUtils.isEmpty(brand)){
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(brand);


    }


}
